package com.demo.youxuanmall.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理所有未捕获的异常
     * 根据请求类型返回不同的响应格式
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleException(Exception e, HttpServletRequest request, Model model) {
        log.error("全局异常处理: {}", e.getMessage(), e);
        
        // 判断请求类型，如果是AJAX请求则返回JSON格式
        if (isAjaxRequest(request)) {
            return handleAjaxException(e);
        } else {
            // 非AJAX请求返回错误页面
            return handleViewException(e, model);
        }
    }
    
    /**
     * 处理AJAX请求的异常，返回JSON格式
     */
    @ResponseBody
    private Result<String> handleAjaxException(Exception e) {
        return Result.error("系统繁忙，请稍后再试: " + e.getMessage());
    }
    
    /**
     * 处理视图请求的异常，返回错误页面
     */
    private ModelAndView handleViewException(Exception e, Model model) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("error", "系统繁忙，请稍后再试");
        mav.addObject("message", e.getMessage());
        mav.addObject("timestamp", System.currentTimeMillis());
        mav.setViewName("error/500");
        return mav;
    }
    
    /**
     * 判断请求是否为AJAX请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestedWith);
    }
} 